<script setup lang="ts">
defineOptions({
  name: "filePreview"
});

import { ref, computed, watch, nextTick } from "vue";
import { PxScrollbar } from "px-ui";
import { fileTypes } from "../utils";

const index = defineModel({ type: Number, default: 0 });

const props = withDefaults(defineProps<{ files: Array<any> }>(), { files: () => [] });

const scrollbarRef = ref<InstanceType<typeof PxScrollbar>>();
const content_width = computed(() => {
  if (!props.files.length) return 0;
  const width_1 = props.files.length * 80;
  const width_2 = (props.files.length - 1) * 16;
  return `${width_1 + width_2}px`;
});

const selectFileHandler = (ind: number) => {
  index.value = ind;
};

watch(
  () => index.value,
  async val => {
    await nextTick();
    const scrollLeft = val * (80 + 16);
    scrollbarRef.value.setScrollLeft(scrollLeft);
  }
);
</script>

<template>
  <px-scrollbar ref="scrollbarRef" class="file-preview-scrollbar">
    <div class="file-preview-content">
      <px-tooltip v-for="(item, ind) in files" :key="item.id" :hide-after="0" :content="item.originalName">
        <div :class="['file-preview-item', index === ind ? 'file-preview-item-active' : '']" @click="selectFileHandler(ind)">
          <px-image v-if="item?.fileType === 'image'" :key="item?.id" :src="item?.fileUrl" fit="contain">
            <template #error>
              <div class="image-slot-wrap">
                <span class="img-text">图片加载失败，请刷新页面。。</span>
              </div>
            </template>
          </px-image>
          <px-icon v-else-if="item?.fileType === 'file'" :size="60">
            <component :is="fileTypes.get(item.filePath)?.icon || fileTypes.get('default').icon" />
          </px-icon>
        </div>
      </px-tooltip>
    </div>
  </px-scrollbar>
</template>

<style lang="scss" scoped>
.file-preview-scrollbar {
  padding-bottom: 16px;

  .file-preview-content {
    display: flex;
    flex-wrap: nowrap;
    gap: 16px;
    align-items: center;
    width: v-bind(content_width);

    .file-preview-item {
      box-sizing: border-box;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 80px;
      height: 80px;
      background-color: #fff;
      border: 1px solid #e6e6e6;
      border-radius: 4px;

      &:hover {
        cursor: pointer;
        border-color: var(--px-color-primary);
      }

      .px-image {
        width: 90%;
        height: 90%;
      }
    }

    .file-preview-item-active {
      border-color: var(--px-color-primary);
    }
  }
}
</style>
